<template>
    <view class="register" :style="{ direction: $store.state.dir }">
        <view class="logo">
            <image src="/static/login/logo.png"></image>
            <text> haloهالو</text>
        </view>
        <view class="login_ul">
            <ul>
                <li>
                    <image src="/static/login/icon_01.png"></image>
                    <text>*</text>
                    <input
                        v-model="name"
                        :placeholder="$t('login.username')"
                        placeholder-style="color: #9E6B47;"
                        type="text"
                    />
                </li>
                <li>
                    <image src="/static/login/icon_02.png"></image>
                    <text>*</text>
                    <input
                        v-model="password"
                        :placeholder="$t('login.password')"
                        placeholder-style="color: #9E6B47;"
                        type="text"
                        maxlength="16"
                    />
                </li>
                <li>
                    <image src="/static/login/icon_03.png"></image>
                    <text>*</text>
                    <input
                        v-model="phone"
                        :placeholder="$t('login.phone')"
                        placeholder-style="color: #9E6B47;"
                        type="text"
                    />
                </li>
                <li>
                    <image src="/static/login/icon_04.png"></image>
                    <text>*</text>
                    <input
                        v-model="code"
                        placeholder="Verification code"
                        placeholder-style="color: #9E6B47;"
                        type="text"
                    />
                    <view
                        class="login_code"
                        @click.stop="handleCode"
                        :style="{ opacity: isCounting ? '0.7' : '1' }"
                    >
                        {{ countdownText }}
                    </view>
                </li>
                <li>
                    <image src="/static/login/icon_05.png"></image>
                    <input
                        v-model="email"
                        :placeholder="$t('login.email')"
                        placeholder-style="color: #9E6B47;"
                        type="text"
                    />
                </li>
                <li>
                    <image src="/static/login/icon_06.png"></image>
                    <input
                        v-model="inviteCode"
                        :placeholder="$t('login.inviteCode')"
                        placeholder-style="color: #9E6B47;"
                        type="text"
                    />
                </li>
            </ul>
        </view>
        <!-- <input-item :name="$t('login.username')" must="1" icon="icon-user">
			<input v-model="name" class="input" type="text" />
		</input-item>

		<phone-input :name="$t('login.phone')" must="1" @change="updatePhoneNumber"></phone-input>
		<input-item :name="$t('login.email')" must="1" icon="icon-email">
			<input v-model="email" class="input" type="text" />
		</input-item>
		<input-item :name="$t('login.password')" must="1" icon="icon-unlock">
			<input password v-model="password" class="input" type="text" />
		</input-item>
		<input-item :name="$t('login.inviteCode')" icon="icon-invite">
			<input v-model="inviteCode" class="input" type="text" />
		</input-item> -->
        <!-- <input-item :name="$t('login.code')" icon="icon-code" :body-style="{ padding: '5px 8px' }">
            <input v-model="code" class="input" type="digit" />
            <u-button :disabled="disableCode" @click="sendCode" style="width: 80px; border-radius: 8px" size="small" type="primary" :text="countText"></u-button>
        </input-item> -->
        <!-- <input-item v-if="type == 2" must="0" custom :name="$t('login.image.user')">
			<image-uploader fileName="personal" type="info" @change="handlePersonalPhotoChange"></image-uploader>
		</input-item>
		<input-item v-if="type == 2" must="0" custom :name="$t('login.image.id')">
			<image-uploader fileName="cert" type="info" @change="handleCertUrlChange"></image-uploader>
		</input-item> -->
        <view class="login-button flex-layout-col flex-center">
            <u-button
                @click="handleSignup"
                style="background: #fa751f; color: #fff"
                size="large"
                shape="circle"
                text="Register"
            ></u-button>
            <p @click.stop="handleLoginRedirect">Log In</p>
        </view>
    </view>
</template>

<script>
import {
    showFailure,
    showMessage,
    showSuccess,
    showAlert,
} from "../../lib/helper";
import { emailCode, register } from "../../lib/service";
import { getSendSms, getRegisterBySms } from "@/lib/business";
import { isValidEgyptianPhoneNumber } from "@/utils/utils";
var timer = null;

export default {
    data() {
        return {
            nickname: "",
            name: "",
            type: 1,
            code: "",
            inviteCode: "",
            email: "",
            phone: "",
            code: "",
            password: "",
            areaCode: "",
            certUrl: "",
            personalPhotoUrl: "",
            isCounting: false, // 是否正在倒计时
            countdown: 60, // 倒计时秒数
            timer: null, // 定时器引用
            showAgree: true, //协议是否选择
            isRotate: false, //是否加载旋转
        };
    },
    onLoad(options) {
        this.type = options.type;
    },
    beforeDestroy() {
        // 组件销毁前清除定时器
        if (this.timer) {
            clearInterval(this.timer);
        }
    },
    computed: {
        countdownText() {
            return this.isCounting ? `${this.countdown}S` : "Get";
        },
    },
    methods: {
        // 开始倒计时
        handleCode() {
            let _this = this;
            if (this.isCounting) return;
            if (!this.phone) {
                showMessage("Please provide your contact phone number");
                return;
            }
            let isPhone = isValidEgyptianPhoneNumber(_this.phone);
            if (!isPhone) {
                showMessage(this.$t("message.phone.wrong"));
                return;
            }
            getSendSms({ mobile: _this.phone })
                .then((res) => {
                    // 开始倒计时
                    _this.startCountdown();
                })
                .catch((res) => {
                    showFailure(this.$t("message.sendCode.failed"));
                });
        },
        startCountdown() {
            this.isCounting = true;
            this.countdown = 60;
            this.timer = setInterval(() => {
                if (this.countdown > 0) {
                    this.countdown--;
                } else {
                    this.stopCountdown();
                }
            }, 1000);
        },
        stopCountdown() {
            this.isCounting = false;
            if (this.timer) {
                clearInterval(this.timer);
                this.timer = null;
            }
        },
        updatePhoneNumber(value) {
            console.log(value);
            let isPhone = isValidEgyptianPhoneNumber(value);
            if (!isPhone) {
                uni.$u.toast(
                    "Please select the correct phone number to submit"
                );
                return;
            }
            this.phone = value;
        },

        handlePersonalPhotoChange(data) {
            var file = data[0];
            this.personalPhotoUrl = file ? file.url : "";
        },
        handleCertUrlChange(data) {
            var file = data[0];
            this.certUrl = file ? file.url : "";
        },
        handleLoginRedirect() {
            uni.redirectTo({
                url: "/pages/login/login",
            });
        },

        // sendCode() {
        //     if (!emailRegex.test(this.email)) {
        //         showAlert(this.$t('message.email.wrong'));
        //         return false;
        //     }
        //     this.disableCode = true;
        //     uni.showLoading();
        //     emailCode(this.email)
        //         .then((res) => {
        //             showMessage(this.$t('message.code.success'));
        //             timer = setInterval(() => {
        //                 this.count--;
        //                 if (this.count <= 0) {
        //                     this.disableCode = false;
        //                     clearInterval(timer);
        //                 }
        //             }, 1000);
        //         })
        //         .catch((res) => {
        //             this.disableCode = false;
        //             uni.hideLoading();
        //         });
        // },
        validateEmail(email) {
            const emailRegex =
                /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/;
            return emailRegex.test(email);
        },
        // handleSignup() {
        // 	//注册
        // 	if (this.isRotate) {
        // 		//判断是否加载中，避免重复点击请求
        // 		return false;
        // 	}
        // 	if (this.showAgree == false) {
        // 		return false;
        // 	}
        // 	this.startReg();
        // },
        handleSignup() {
            //注册
            if (this.isRotate) {
                //判断是否加载中，避免重复点击请求
                return false;
            }
            this.handleMsg();
        },
        handleMsg() {
            if (!this.name) {
                showAlert(this.$t("message.emety.username"));
                return false;
            }
            if (!this.password) {
                showAlert(this.$t("message.emety.password"));
                return false;
            }
            if (this.password.length < 6) {
                showAlert("Password must be at least 6 characters long");
                return false;
            }
            if (!this.phone) {
                showAlert(this.$t("message.emety.phone"));
                return false;
            }
            let isPhone = isValidEgyptianPhoneNumber(this.phone);
            if (!isPhone) {
                showAlert(this.$t("message.phone.wrong"));
                return;
            }
            if (!this.code) {
                showAlert(this.$t("message.emety.code"));
                return false;
            }
            uni.showLoading();
            this.isRotate = true;
            getRegisterBySms({
                name: this.name,
                phone: this.phone,
                email: this.email,
                vcode: this.code,
                inviteCode: this.inviteCode,
                type: this.type,
                password: this.password,
            })
                .then((res) => {
                    if (res.statusCode == 0) {
                        uni.hideLoading();
                        showSuccess();
                        this.isRotate = false;
                        this.handleLoginRedirect();
                    } else {
                        this.isRotate = false;
                        uni.showToast({
                            title: res.message,
                            icon: "none",
                        });
                    }
                })
                .catch((res) => {
                    uni.hideLoading();
                    this.isRotate = false;
                });
        },

        startReg() {
            if (!this.name) {
                showAlert(this.$t("message.emety.username"));
                return false;
            }
            let isPhone = isValidEgyptianPhoneNumber(this.phone);
            if (!isPhone) {
                showAlert(this.$t("message.phone.wrong"));
                return;
            }
            // const isValid = this.validateEmail(this.email);
            // if (!isValid) {
            // 	showAlert(this.$t('message.email.wrong'));
            // 	return;
            // }

            if (this.password.length <= 0) {
                showAlert(this.$t("message.emety.password"));
                return false;
            }

            // if (this.code.length <= 0) {
            //     showAlert(this.$t('message.code.wrong'));
            //     return false;
            // }

            // if (this.type == 2) {
            // 	if (this.personalPhotoUrl.length <= 0) {
            // 		showAlert(this.$t('message.emety.personalPhoto'));
            // 		return false;
            // 	}
            // 	if (this.certUrl.length <= 0) {
            // 		showAlert(this.$t('message.emety.cert'));
            // 		return false;
            // 	}
            // }
            uni.showLoading();
            this.isRotate = true;
            register({
                name: this.name,
                phone: this.phone,
                email: this.email,
                inviteCode: this.inviteCode,
                password: this.password,
                emailCaptcha: this.code,
                certUrl: this.certUrl,
                personalPhotoUrl: this.personalPhotoUrl,
                type: this.type,
            })
                .then((res) => {
                    if (res.statusCode == 0) {
                        uni.hideLoading();
                        showSuccess();
                        this.isRotate = false;
                        this.handleLoginRedirect();
                    } else {
                        this.isRotate = false;
                        uni.showToast({
                            title: res.message,
                            icon: "none",
                        });
                    }
                })
                .catch((res) => {
                    uni.hideLoading();
                    this.isRotate = false;
                });
        },
    },
};
</script>

<style lang="scss" scoped>
.register {
    padding: 0 30px;

    .login-button {
        margin-top: 20px;
        p {
            margin-top: 140rpx;
            font-weight: bold;
        }
    }

    input {
        width: 80%;
    }
}
.logo {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-top: 70rpx;

    image {
        width: 70rpx;
        height: 84rpx;
    }

    text {
        display: inline-block;
        font-size: 40rpx;
        color: red;
        font-weight: bold;
    }
}
.login_ul {
    margin-top: 80rpx;

    ul {
        li {
            height: 96rpx;
            border-radius: 60rpx;
            border: 2rpx solid #e8d9cf;
            display: flex;
            align-items: center;
            padding: 0 38rpx;
            margin-bottom: 44rpx;
            position: relative;

            image {
                width: 36rpx;
                height: 36rpx;
            }

            text {
                color: red;
            }

            input {
                display: inline-block;
                margin-left: 8rpx;
                font-size: 32rpx;
                color: #9e6b47;
            }

            .login_code {
                position: absolute;
                right: 30rpx;
                color: #fc721a;
            }
        }
    }
}
</style>
